package com.example.demo01.Socket.Client;

import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.StrUtil;
import com.example.demo01.Utils.ArrayUtils;
import com.example.demo01.VO.TelNo00;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteOrder;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;


@Slf4j
public class HeartbeatHandler extends SimpleChannelInboundHandler {

    private ScheduledExecutorService executorService;
    private ScheduledFuture<?> heartbeatFuture;
    @Override
    public void channelActive(ChannelHandlerContext ctx) {

        executorService = Executors.newScheduledThreadPool(1);
        heartbeatFuture=executorService.scheduleAtFixedRate(()->{

            log.info("HeartbeatHandler  scheduleAtFixedRate...........");
            TelNo00 telNo00=new TelNo00();

            byte[] tel= StrUtil.bytes(telNo00.getTelNo());
            byte[] content=ByteUtil.longToBytes(System.currentTimeMillis(), ByteOrder.BIG_ENDIAN);

            byte[] body= ArrayUtils.concatByte(tel,content);

            telNo00.setBody(body);
            ctx.writeAndFlush(telNo00);
        },0,5, TimeUnit.SECONDS);
        log.info("HeartbeatHandler  channelActive...........");

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        // 取消定时任务
        heartbeatFuture.cancel(true);

        // 关闭ScheduledExecutorService
        executorService.shutdown();

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {


    }
}
